package znet

import (
	"errors"
	"log"
	"sync"
	"zinxp/ziface"
)

/*
	连接管理模块
 */
type ConnManager struct {
	//管理的连接信息
	connections map[uint32]ziface.IConnection
	//读写连接的读写锁
	connLock sync.RWMutex
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]ziface.IConnection),
		connLock:    sync.RWMutex{},
	}
}

func (connMgr *ConnManager)Add(conn ziface.IConnection)  {
	//保护共享资源Map 加写锁
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	connMgr.connections[conn.GetConnID()] = conn
	log.Println("connection add to ConnManager successfully: conn num= ",connMgr.Len())
}

func (connMgr *ConnManager)Remove(conn ziface.IConnection)  {
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()
	delete(connMgr.connections,conn.GetConnID())
	log.Println("connection remove successfully!connID=",conn.GetConnID(),"conn num= ",connMgr.Len())
}

func (connMgr *ConnManager)Get(connId uint32) (ziface.IConnection,error) {
	connMgr.connLock.RLock()
	defer connMgr.connLock.RUnlock()
	if conn,ok := connMgr.connections[connId];ok{
		return conn,nil
	}else {
		return nil,errors.New("Connection not found!")
	}
}

func (connMgr *ConnManager)Len() int {
	return len(connMgr.connections)
}

func (connMgr *ConnManager)ClearConn()  {
	connMgr.connLock.Lock()
	defer connMgr.connLock.Unlock()

	for connID,conn := range connMgr.connections{
		conn.Stop()
		delete(connMgr.connections,connID)
	}

	log.Println("Clear All Connections successfully! conn num= ",connMgr.Len())
}